<?php
/**
 * Bdat Site development
 * @author Will Skates
 */

/*----------------------------------------------------------------------------------------------------*/

/**
 * Class for aggregating content into the database for presentation in Masonry blocks.
 * @author Will Skates
 */
class aggregator extends CI_Controller {
	
	public $userList = array();
	
	public $loaded = array();
	
	public $magicTag = '#bdat';
	
	/**
	 * Function is run when the page is loaded.
	 * @return Void
	 */
	public function index() {}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Aggregate new content into the database.
	 * @return Void
	 */
	public function aggregate()
	{
		
		//Load in the helper files and models that we are going to be using.
		$this->load->helper('simplexml');
		$this->load->library('Rss');
		$this->load->model('users/User');
		
		//Get an array of all of the users.
		$this->userList = $this->User->getAll();
		$this->rss->set_items_limit(10);
		
		foreach ( $this->userList as $key=>$user ) {
			
			//For each user, aggregate their tweets first and their rss feed items second.
			
			//Make sure that the user is the guest tweeter first.
			if ( $user->profile->isguesttweeter && strlen($user->profile->twitter) > 0 ) {
				$this->aggregateTweets(
						$user->profile->twitter,
						$user->id
				);
			}
			
			//Check that the user has supplied a link to an rss feed first.
			if ( strlen(trim($user->profile->feed)) > 0 ) {
				$this->aggregateShowcase(
						$user->profile->feed,
						$user->id
				);
			}
			
		}
		
		
		if ( count($this->loaded) ) {
			foreach ( $this->loaded as $k=>$v ) {
				echo $v . '<br/><br/>';
			}
		} else {
			echo 'There was nothing new to aggregate.';
		}

	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Aggregate all feed items for the current user.
	 * @param	$link	- The url to the rss feed that needs to be aggregated.
	 * @param	$id		- The unique id for the user who's feed we are aggregating.
	 * @return	void.
	 */
	public function aggregateShowcase( $link, $id )
	{
		
		//set the url and get the data as an array.
		$this->rss->set_url( array($link) );
		$data = simplexml2array( $this->rss->parse() );
		
		//Check each item and....
		foreach ( $data as $k=>$v ) {
			
			//If we can't find the magic tag in the title or the content then don't bother trying to pass it.
			if ( mb_strpos(strtolower($v['title']), $this->magicTag) === false
				 || mb_strpos(strtolower($v['content']), $this->magicTag) === false ) {
				unset($data[$k]);
			}
			
		}
		
		//If we havent got any data then don't bother trying to pass it.
		if ( sizeof($data) == 0 ) { return; }
		
		//We need to check that the content for the items don't already exist so comile a list of all the titles...... (1)
		$titles = array();
			
		foreach ($data  as $key=>$value) {
			$data[$key]['title'] = $this->makeTitle($value['title']);
			$titles[] = '\'' . $data[$key]['title'] . '\''; //<-This makes sure that you can just enter the title of the passage in the query.
		}
			
		//(1) and get a list of results which contain those titles.
		$query  = $this->db->query( 'SELECT title FROM showcase WHERE title IN (' . implode(',',$titles) . ') AND author=' . $id );
		$result = $query->result();
		
		if ( sizeof( $result ) > 0 ) {
			
			//Go through each piece of data from the rss feed and for each one.....
			foreach ( $data as $key=>$value ) {
					
				//go through each database result.
				foreach ($result as $num=>$res ) {
					
					//If it exists...
					if ( $value['title'] == $res->title ) {
						
						//Then get rid of it and go to the next one.
						unset($data[$key]);
						continue 2;
						
					}
					
				}
					
			}
				
		}
		
		//Load the model for the showcase item.
		$this->load->model('Showcase');
		
		//For each available showcase item....
		foreach ($data as $key=>$value) {
			
			//Set the data for the showcase item and then store it.
			$this->Showcase->title 			= $value['title'];
			$this->Showcase->content 		= $value['content'];
			$this->Showcase->timestamp 		= strtotime($value['published']);
			$this->Showcase->link 			= $value['link'];
			$this->Showcase->author			= $id;
			$this->Showcase->approved 		= 0;
			$this->Showcase->published 		= 0;
			$this->Showcase->sticky 		= 0;
			$this->Showcase->insert();

			$this->loaded[] = 'Showcase: ' . $this->Showcase->title;
			
		}
			
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Aggregate all tweets for the current user.
	 * @param	$link	- The url to the rss feed that needs to be aggregated.
	 * @param	$id		- The unique id for the user who's feed we are aggregating.
	 * @return	void.
	 */
	
	public function aggregateTweets( $link, $id ) 
	{
		
		//Make a useable link for this users twitter profile.
		$this->load->helper('twitter');
		$link = 'http://twitter.com/statuses/user_timeline/' . getName($link) . '.rss';
		
		//Load in the item.
		$this->rss->set_url($link);
		$data = simplexml2array( $this->rss->parse() );

		//Check each item and....
		foreach ( $data as $k=>$item ) {
			
			//If we can't find the magic tag in the title then don't bother trying to pass it.
			if ( mb_strpos(strtolower($item['title']), $this->magicTag) === false ) {
				unset($data[$k]);
			}
			
		}

		$list = array();
		
		//If we have any data to parse...
		if ( sizeof($data) > 0 ) {
			
			//We need to check that the content for the items don't already exist so comile a list of all the titles...... (1)
			$titles = array();
			
			foreach ($data  as $key=>$value) {
				$data[$key]['link'] = $this->makeTitle($value['link']);
				$titles[] = '\'' . $data[$key]['link'] . '\''; //<-This makes sure that you can just enter the title of the passage in the query.
			}
			
			//(1) and get a list of results which contain those titles.
			$query  = $this->db->query( 'SELECT title FROM tweets WHERE title IN (' . implode($titles) . ') AND author = ' . $id );
			$result = $query->result();
			
			if ( sizeof( $result ) > 0 ) {
				
				//Go through each piece of data from the twitter rss feed and for each one.....
				foreach ( $data as $key=>$value ) {
					
					//go through each database result.
					foreach ($result as $num=>$res ) {
						
						//If it exists...
						if ( $value['link'] == $res->title ) {
							
							//Then get rid of it and go to the next one.
							unset($data[$key]);
							continue 2;
							
						}
						
					}
					
				}
				
			}
			
		}
		
		
		//Store those tweets.
		$this->load->model('Tweet');
		
		//For each available showcase item....
		foreach ($data as $key=>$value) {
			//Set the data for the showcase item and then store it.
			$this->Tweet->title = $this->makeTitle($value['link']);
			$this->Tweet->content = $this->getTwitterMessage($value['title']);
			$this->Tweet->timestamp = strtotime($value['pubDate']);
			$this->Tweet->author = $id;
			$this->Tweet->approved = 0;
			$this->Tweet->published = 0;
			$this->Tweet->sticky = 0;
			$this->Tweet->insert();
			$this->loaded[] = 'Tweet: ' . $this->Tweet->title;
		}
		
		
	}
	
	/**
	 * Make a title from a loaded string.
	 * @param 	$title	- The string dictating the title as it came from the feed.
	 * @return 	String	- The new title.
	 */
	public function makeTitle( $title )
	{
		return htmlentities ( $title, ENT_QUOTES, 'UTF-8' );
	}
	
	/**
	 * Get the actual twitter message from the string provided in the rss feed.
	 * @param 	$content	- The original content for the tweet.
	 * @return  String		- The parsed content.
	 */
	public function getTwitterMessage( $content )
	{
		$c = 1;
		return end(explode(':',$content,$c));
	}
	
	/**
	 * Make a reference for an item in a table relating to a user.
	 * @param	$id		- The users unique identifier.
	 * @param	$title	
	 * @param $content
	 * @return unknown_type
	 */
	public function makeReference( $id, $title, $content )
	{
		$title = md5( $table . $id . substr($title,0,14) . substr($content,0,20) );
	}
	
	
	
}